<template>
<Cascader v-bind="$attrs" v-on="$listeners" :data="data" v-model="val" :placeholder="placeholder"></Cascader>
</template>

<script>
import {
    transformTozTreeFormat
} from '@/utils/tool'
export default {
    props: {
        //只接收行政区域id
        value: {
            type: [String, Array, Number]
        }
    },
    data() {
        return {
            data: [],
            val: [],
            placeholder: "数据加载中...",
            items: [],
            path: []
        }
    },
    watch: {
        value: "initData"
    },
    methods: {
        //获取初始的数据
        async loadData() {
            let res = await this.$api.position.getBkccpositionTree()
            res.map(pos => {
                pos.value = pos.id
                pos.label = pos.text
            })

            this.items = JSON.parse(JSON.stringify(res))
            this.data = transformTozTreeFormat({
                key: "id",
                parentKey: "pid",
                childKey: "children"
            }, res)

            this.placeholder = "请选择岗位"
        },
        async initData(val) {
            if (val == undefined || val == -1 || val.toString() == "") {
                this.val = []
            } else {
                if (this.items.length > 0) {
                    let path = this.items.find(item => item.id == val).path.split(":")
                    this.val = path.slice(0, path.length - 1)
                } else {
                    let pos = await this.$api.position.getPositionByPosid({
                        posid: val
                    })
                    if (pos.rows.length > 0) {
                        let path = pos.rows[0].nodepath
                        let pathArray = pos.rows[0].nodepath.split(":")
                        this.val = pathArray.slice(0, pathArray.length - 1)
                    }
                }
            }
        },
    },
    created() {
        this.loadData()
    }
}
</script>

<style lang="less" scoped>

</style>
